package com.platform.study.thread.threadpool;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 13-1-5
 * Time: 下午4:01
 * To change this template use File | Settings | File Templates.
 */
public class ThreadPool {

    private BlockingQueue taskQueue = null;
    private List<TaskThread> threads = new ArrayList<TaskThread>();
    private boolean isStopped = false;

    /**
     * Create a new ThreadPool
     * @param noOfThreads Initiate num of threads in the thread pool线程池的初始化线程数
     * @param maxNoOfTasks Max num of threads in the thread pool线程池的最大线程数
     */
    public ThreadPool(int noOfThreads, int maxNoOfTasks) {
        taskQueue = new BlockingQueue(maxNoOfTasks);

        for (int i = 0; i < noOfThreads; i++) {
            threads.add(new TaskThread(taskQueue));
        }
        for (TaskThread thread : threads) {
            thread.start();
        }
    }

    /**
     *
     * @param task
     */
    public synchronized void execute(Runnable task){
        if(this.isStopped) {
            throw new IllegalStateException("ThreadPool is stopped");
        }
        try {
            this.taskQueue.enqueue(task);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    /**
     *
     */
    public synchronized void stop() {
        this.isStopped = true;
        for (TaskThread thread : threads) {
            thread.interrupt();
        }
    }
}
